package com.typing.battle.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.typing.battle.listener.OnDataSyncCompleteListener;
import com.typing.battle.value.ServerComunicationDTO;

public class ServerComunicationUtil {
	//public static final String THIRD_PARTY_SERVER_URL = "http://210.126.12.230/battle/app";
	//public static final String LOGIN_URI = "http://210.126.12.230/battle/j_spring_security_check";
	
	public static final String THIRD_PARTY_SERVER_URL = "http://www.typoong.com/app/battle";
	public static final String LOGIN_URI = "http://www.typoong.com/j_spring_security_check";
	
	public static final int TYPE_SEND_MESSAGE = 0;
	public static final int TYPE_SEND_SPEED = 1;
	public static final int TYPE_SEND_INVITE = 2;
	public static final int TYPE_BATTLE_INVITE = 3;
	public static final int TYPE_TYPING_START =4;
	
	public static final int TYPE_MEMBER_JOIN = 10;
	public static final int TYPE_MEMBER_QUIT = 11;
	public static final int TYPE_MEMBER_UPDATE = 12;
	public static final int TYPE_MEMBER_DETAIL = 13;
	
	public static final int TYPE_FRIEND_INSERT = 20;
	public static final int TYPE_FRIEND_DELETE = 21;
	public static final int TYPE_FRIEND_UPDATE = 22;
	public static final int TYPE_FRIEND_SELECT = 23;
	public static final int TYPE_FRIEND_DETAIL = 24;
	
	public static final int  TYPE_CHAT_ROOM_JOIN = 30;
	public static final int  TYPE_CHAT_ROOM_QUIT = 31;
	public static final int  TYPE_CHAT_ROOM_CREATE = 32;
	public static final int  TYPE_CHAT_ROOM_DROP = 33;	
	public static final int  TYPE_CHAT_ROOM_SELECT = 34;	
	public static final int  TYPE_CHAT_ROOM_DETAIL = 35;
	public static final int  TYPE_CHAT_ROOM_BANISH = 36;
	public static final int  TYPE_CHAT_ROOM_RANDOM = 37;
	public static final int  TYPE_CHAT_ROOM_MASTER_JOIN = 38;
	
	public static final int  TYPE_TIME_ATTACK_LIST = 40;	
	public static final int  TYPE_TIME_ATTACK_INSERT = 41;	
	public static final int  TYPE_TIME_ATTACK_DETAIL = 42;	
	public static final int  TYPE_TIME_ATTACK_RANKING = 43;	
	
	public static final int  TYPE_SERVER_SYNC = 50;
	public static final int  TYPE_SERVER_SYNC_START = 51;
	public static final int  TYPE_SERVER_SYNC_END = 52;
	public static final int  TYPE_FILE_UPLOAD = 53;
	
	public static final int RETURN_TYPE_STRING = 0;
	public static final int RETURN_TYPE_JSON = 1;
	public static final int RETURN_TYPE_NULL = 2;
	
	private static final int timeOutInterval = 10 * 1000;
	
	public static String SESSION_KEY;
	
	private static String getURI(int type){
		String uri = null;
		switch(type){
		case TYPE_SEND_MESSAGE :
			uri = THIRD_PARTY_SERVER_URL + "/messageInsert;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_SEND_SPEED : 
			uri = THIRD_PARTY_SERVER_URL + "/battleInsert;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_SEND_INVITE : 
			uri = THIRD_PARTY_SERVER_URL + "";
			break;
		case TYPE_BATTLE_INVITE : 
			uri = THIRD_PARTY_SERVER_URL + "/friendInvite;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_TYPING_START : 
			uri = THIRD_PARTY_SERVER_URL + "/battleStart;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_MEMBER_JOIN :
			uri = THIRD_PARTY_SERVER_URL + "/memberJoin";
			break;
		case TYPE_MEMBER_QUIT : 
			uri = THIRD_PARTY_SERVER_URL + "";
			break;
		case TYPE_MEMBER_UPDATE : 
			uri = THIRD_PARTY_SERVER_URL + "/memberUpdate;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_MEMBER_DETAIL : 
			uri = THIRD_PARTY_SERVER_URL + "/memberDetail;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_FRIEND_INSERT :
			uri = THIRD_PARTY_SERVER_URL + "/friendInsert;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_FRIEND_DELETE : 
			uri = THIRD_PARTY_SERVER_URL + "/friendDelete;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_FRIEND_UPDATE : 
			uri = THIRD_PARTY_SERVER_URL + "/friendUpdate;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_FRIEND_SELECT : 
			uri = THIRD_PARTY_SERVER_URL + "/friendList;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_FRIEND_DETAIL : 
			uri = THIRD_PARTY_SERVER_URL + "";
			break;
		case TYPE_CHAT_ROOM_JOIN :
			uri = THIRD_PARTY_SERVER_URL + "/chatRoomJoin;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_CHAT_ROOM_QUIT : 
			uri = THIRD_PARTY_SERVER_URL + "/chatRoomQuit;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_CHAT_ROOM_CREATE : 
			uri = THIRD_PARTY_SERVER_URL + "/chatRoomCreate;jsessionid=" + SESSION_KEY;
			break;		
		case TYPE_CHAT_ROOM_DROP : 
			uri = THIRD_PARTY_SERVER_URL + "";
			break;
		case TYPE_CHAT_ROOM_SELECT : 
			uri = THIRD_PARTY_SERVER_URL  + "/chatRoomList;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_CHAT_ROOM_DETAIL : 
			uri = THIRD_PARTY_SERVER_URL + "/chatRoomJoinMemberList;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_CHAT_ROOM_BANISH : 
			uri = THIRD_PARTY_SERVER_URL + "/chatRoomBanish;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_CHAT_ROOM_RANDOM : 
			uri = THIRD_PARTY_SERVER_URL + "/randomChat;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_CHAT_ROOM_MASTER_JOIN : 
			uri = THIRD_PARTY_SERVER_URL + "/chatRoomMasterJoin;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_TIME_ATTACK_LIST : 
			uri = THIRD_PARTY_SERVER_URL + "/timeAttackList;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_TIME_ATTACK_INSERT : 
			uri = THIRD_PARTY_SERVER_URL + "/timeAttackInsert;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_TIME_ATTACK_DETAIL : 
			uri = THIRD_PARTY_SERVER_URL + "/timeAttackDetail;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_TIME_ATTACK_RANKING : 
			uri = THIRD_PARTY_SERVER_URL + "/timeAttackRankList;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_SERVER_SYNC : 
			uri = THIRD_PARTY_SERVER_URL + "/messageList;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_SERVER_SYNC_START : 
			uri = THIRD_PARTY_SERVER_URL + "/pollingStart;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_SERVER_SYNC_END : 
			uri = THIRD_PARTY_SERVER_URL + "/pollingEnd;jsessionid=" + SESSION_KEY;
			break;
		case TYPE_FILE_UPLOAD : 
			uri = THIRD_PARTY_SERVER_URL + "/fileUplad;jsessionid=" + SESSION_KEY;
			break;
		}
		return uri;
	}
	public static void serverAction(final ServerComunicationDTO dto,final Context context) throws Exception{
		serverAction(dto, context,null);
	}
	public static void serverAction(final ServerComunicationDTO dto,final Context context ,final OnDataSyncCompleteListener listener) throws Exception{
		//if(checkNetwokState(context)){
		AsyncTask<String, Void, Object> task = new AsyncTask<String, Void, Object>() {
			String msg;
			ProgressDialog progressDialog;
			protected Object doInBackground(String... x) {
				KLog.d(context,"doInBackground :: ActionType ===>>"+dto.getActionType());
				DefaultHttpClient client = new DefaultHttpClient();
				HttpPost request = new HttpPost(getURI(dto.getActionType()));
				HttpResponse response = null;				
				List<NameValuePair> params = getParameterList(dto);
				msg = "Unkown Error!!";
				try {
					request
							.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					HttpParams httpParams = client.getParams();
					if(dto.getTimeoutInterval() > 0){
						HttpConnectionParams.setConnectionTimeout(httpParams, dto.getTimeoutInterval());
						HttpConnectionParams.setSoTimeout(httpParams, dto.getTimeoutInterval());
					}else{
						HttpConnectionParams.setConnectionTimeout(httpParams, timeOutInterval);
						HttpConnectionParams.setSoTimeout(httpParams, timeOutInterval);
					}
					
					response = client.execute(request);
					
					return getResponse(dto.getResponseType(),response);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					msg = e.getMessage();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
					msg = e.getMessage();
				}  catch(ConnectTimeoutException e){
					Log.d("timeout",e.getMessage());
					msg = "서버가 응답이 없습니다.";
//					showNotify("서버가 응답이 없습니다.",context);
//					throw e;
				} catch(SocketException e){
					Log.d("socket",e.getMessage());
					msg = "네트웍이 연결이 안됐습니다.";
//					showNotify("네트웍이 연결이 안됐습니다.",context);
//					throw e;
				}  catch (Exception e) {
					e.printStackTrace();
					msg = e.getMessage();
//					throw e;
				} 
				return null;
	    	}
			protected void onPreExecute() {
				try{
					if(progressDialog!=null){
//		    			progressDialog.cancel();
		    			progressDialog.dismiss();
		    		}
				}catch (Exception e) {
				}
				if(listener == null)	return;
	    			
	    		//else
	    		progressDialog = new ProgressDialog(context);
	    		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    		progressDialog.setMessage("Loading...");
	    		progressDialog.show();
				
			}
			protected void onPostExecute(Object result) {
				try{
			    	if(progressDialog!=null){
			    		progressDialog.dismiss();
			    	}
			    	progressDialog = null;
				}catch (Exception e) {
				}
				KLog.d(context,"onPostExecute :: result ===>>"+result);
				if(listener==null)	return;
				
				if(result==null)
					listener.onSyncComplete(OnDataSyncCompleteListener.RESULT_SYNC_FAIL,dto , msg);
				else
					listener.onSyncComplete(OnDataSyncCompleteListener.RESULT_SYNC_SUCCESS,dto , result);
			}
		};
//		if(TypingBattleRootActivity.isICS())
//			task.excu
//		else 
			task.execute();
		

		//}
	}
	
	public static Object pollingAction(ServerComunicationDTO dto,Context context) throws IOException{
		//if(checkNetwokState(context)){
			DefaultHttpClient client = new DefaultHttpClient();
			HttpPost request = new HttpPost(getURI(dto.getActionType()));
			HttpResponse response = null;
			
			List<NameValuePair> params = getParameterList(dto);
			
			try {
				request
						.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				HttpParams httpParams = client.getParams();
				if(dto.getTimeoutInterval() > 0){
					HttpConnectionParams.setConnectionTimeout(httpParams, dto.getTimeoutInterval());
					HttpConnectionParams.setSoTimeout(httpParams, dto.getTimeoutInterval());
				}else{
					HttpConnectionParams.setConnectionTimeout(httpParams, timeOutInterval);
					HttpConnectionParams.setSoTimeout(httpParams, timeOutInterval);
				}
				
				response = client.execute(request);
				
				return getResponse(dto.getResponseType(),response);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			}  catch(ConnectTimeoutException e){
				Log.d("timeout",e.getMessage());
				showNotify("서버가 응답이 없습니다.",context);
				throw e;
			} catch(SocketException e){
				Log.d("socket",e.getMessage());
				showNotify("네트웍이 연결이 안됐습니다.",context);
				throw e;
			}  catch (IOException e) {
				//e.printStackTrace();
				throw e;
			} 
		//}
		return null;
	}
	
    
	public static Object login(ServerComunicationDTO dto,Context context) throws IOException{
		//if(checkNetwokState(context)){
			DefaultHttpClient client = new DefaultHttpClient();
			HttpPost requestLogin = new HttpPost(LOGIN_URI + "?");
			HttpResponse response = null;
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("j_username", dto.getUserEmail()));
			params.add(new BasicNameValuePair("j_password", dto.getUserPassword()));
			params.add(new BasicNameValuePair("_spring_security_remember_me",
					"true"));
			try {
				requestLogin
						.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				HttpParams httpParams = client.getParams();
				HttpConnectionParams.setConnectionTimeout(httpParams, timeOutInterval);
				HttpConnectionParams.setSoTimeout(httpParams, timeOutInterval);
	
				response = client.execute(requestLogin);
				
				return getResponse(dto.getResponseType(),response);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			}  catch(ConnectTimeoutException e){
				Log.d("timeout",e.getMessage());
				showNotify("서버가 응답이 없습니다.",context);
				throw e;
			} catch(SocketException e){
				StringBuffer sb = new StringBuffer();
				for(int i=0; i < e.getStackTrace().length ; i++){
					sb.append(e.getStackTrace()[i].toString() + "\n");
				}
				Log.d("socket",sb.toString());
				showNotify("네트웍이 연결이 안됐습니다.",context);
				throw e;
			} catch (IOException e) {			
				throw e;
			}
		//}
		return null;
	}
	public static void battleStart(ServerComunicationDTO dto,Context context) throws IOException{
		//if(checkNetwokState(context)){
			StringBuffer postDataBuilder = new StringBuffer();
			postDataBuilder.append("userEmail="+dto.getUserEmail());
			postDataBuilder.append("&chatRoomId="+dto.getChatRoomId());
			postDataBuilder.append("&sendType="+dto.getSendType());
			
			byte[] postData = postDataBuilder.toString().getBytes("UTF8");
			HttpURLConnection conn = null;
			try{
				URL url = new URL(getURI(TYPE_TYPING_START));
				
				conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(timeOutInterval);
				conn.setDoOutput(true);
				conn.setUseCaches(false);
				conn.setRequestMethod("POST");
				conn.setRequestProperty("Content-Type",
						"application/x-www-form-urlencoded");
				conn.setRequestProperty("Content-Length",
						Integer.toString(postData.length));
				OutputStream out = conn.getOutputStream();
				out.write(postData);
				//out.flush();
				//out.close();
				//conn.setReadTimeout(10);
				conn.getInputStream();
			}catch(ConnectTimeoutException e){
				Log.d("timeout",e.getMessage());
				showNotify("서버가 응답이 없습니다.",context);
				throw e;
			} catch(SocketException e){
				Log.d("socket",e.getMessage());
				showNotify("네트웍이 연결이 안됐습니다.",context);
				throw e;
			}
		//}
	}

	public static Object uploadFile(Context context, Bitmap image , String email) {
		//String exsistingFileName = imagePath;
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String urlString = "http://192.168.10.1/test.asp";
		HttpURLConnection conn;
		DataOutputStream dos;

		try {

			/*FileInputStream fileInputStream = new FileInputStream(
					exsistingFileName);
			InputStreamReader isr = new InputStreamReader(fileInputStream);
			char[] inputBuffer = new char[fileInputStream.available()];
			isr.read(inputBuffer);
			String readString = new String(inputBuffer);

			Log.d("Test", "from file" + readString);*/
			// tv.setText("from file"+readString); // ----------> It is reading
			// text from file.

			URL url = new URL(THIRD_PARTY_SERVER_URL+"/fileUpload;jsessionid=" + SESSION_KEY);

			// Open a HTTP connection to the URL

			conn = (HttpURLConnection) url.openConnection();

			// Allow Inputs
			conn.setDoInput(true);

			// Allow Outputs
			conn.setDoOutput(true);

			// Don't use a cached copy.
			conn.setUseCaches(false);

			// Use a post method.
			conn.setRequestMethod("POST");

			conn.setRequestProperty("Connection", "Keep-Alive");

			conn.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			ByteArrayOutputStream bao = new ByteArrayOutputStream();
			image.compress(Bitmap.CompressFormat.JPEG, 90, bao);
			byte [] ba = bao.toByteArray();

			dos = new DataOutputStream(conn.getOutputStream());
			Log.d("zzzzzzz",""+ba.length);
			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\"imageFile\";filename=\""
					+ email + "_image.jpg" + "\"" + lineEnd);
			dos.writeBytes(lineEnd);
			dos.write(ba);
			// Log.e(Tag,"Headers are written");

			// create a buffer of maximum size
			//int maxBufferSize = 1024;
			//int bytesAvailable = fileInputStream.available();
			//int bufferSize = Math.min(0, maxBufferSize);
			//byte[] buffer = new byte[maxBufferSize];

			// read file and write it into form...

			//int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			/*while (bytesRead > 0) {
				dos.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}*/

			// send multipart form data necesssary after file data...

			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

			// close streams
			// Log.e(Tag,"File is written");
			//fileInputStream.close();
			dos.flush();
			dos.close();
			conn.getInputStream();	
		} catch (Exception e) {

			Log.e("ERROR", "this is error : " + e.toString());
			// tv.setText("this is error"+e.toString());
		}

		return null;

	}
	private static Object getResponse(int type,HttpResponse response){
		
		BufferedReader reader = null;
		StringBuffer sb = null;
		String line = null;
		try{
			switch(type){
			case RETURN_TYPE_STRING :
				reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8);
				sb = new StringBuffer();
				line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				return sb.toString();
			case RETURN_TYPE_JSON :
				reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8);
				sb = new StringBuffer();
				line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				JSONArray array = new JSONArray(sb.toString());
				return array;
			case RETURN_TYPE_NULL :
				return null;
			default:
				return null;
			}
		}catch(IOException e){
			e.printStackTrace();
		}catch (JSONException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(reader != null){
					reader.close();
				}
			}catch(IOException e){
				e.printStackTrace();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return null;
	}	
		
	private static List<NameValuePair> getParameterList(
			ServerComunicationDTO dto) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("sendType", "" + dto.getSendType()));
		if (dto.getUserEmail() != null) {
			params.add(new BasicNameValuePair("userEmail", dto.getUserEmail()));
		}
		if (dto.getChatRoomId() != null) {
			params.add(new BasicNameValuePair("chatRoomId", dto.getChatRoomId()));
		}
		if (dto.getReceiveEmail() != null) {
			params.add(new BasicNameValuePair("receiveEmail", dto
					.getReceiveEmail()));
		}
		if (dto.getChatRoomName() != null) {
			params.add(new BasicNameValuePair("chatRoomName", dto
					.getChatRoomName()));
		}
		if (dto.getChatRoomOwner() != null) {
			params.add(new BasicNameValuePair("chatRoomOwner", dto
					.getChatRoomOwner()));
		}
		if (dto.getChatRoomType() != null) {
			params.add(new BasicNameValuePair("chatRoomType", dto
					.getChatRoomType()));
		}
		if (dto.getMaxPeopleCount() != null) {
			params.add(new BasicNameValuePair("maxPeopleCount", dto
					.getMaxPeopleCount()));
		}
		if (dto.getUserPassword() != null) {
			params.add(new BasicNameValuePair("userPassword", dto
					.getUserPassword()));
		}
		if (dto.getUserRegKey() != null) {
			params.add(new BasicNameValuePair("userRegKey", dto.getUserRegKey()));
		}
		if (dto.getUserPhoneNo() != null) {
			params.add(new BasicNameValuePair("userPhoneNo", dto
					.getUserPhoneNo()));
		}
		if (dto.getUserDescription() != null) {
			params.add(new BasicNameValuePair("userDescription", dto
					.getUserDescription()));
		}
		if (dto.getUserName() != null) {
			params.add(new BasicNameValuePair("userName", dto.getUserName()));
		}
		if (dto.getUserImage() != null) {
			params.add(new BasicNameValuePair("userImage", dto.getUserImage()));
		}
		if (dto.getTargetEmail() != null) {
			params.add(new BasicNameValuePair("targetEmail", dto
					.getTargetEmail()));
		}
		if (dto.getMsg() != null) {
			params.add(new BasicNameValuePair("msg", dto.getMsg()));
		}
		if (dto.getFrom() != null) {
			params.add(new BasicNameValuePair("from", dto.getFrom()));
		}
		if (dto.getTypingSpeed() != null) {
			params.add(new BasicNameValuePair("typingSpeed", dto
					.getTypingSpeed()));
		}
		if (dto.getTypingAccuracy() != null) {
			params.add(new BasicNameValuePair("typingAccuracy", dto
					.getTypingAccuracy()));
		}
		if (dto.getTypingTime() != null) {
			params.add(new BasicNameValuePair("typingTime", dto.getTypingTime()));
		}
		if (dto.getSentenceId() != null) {
			params.add(new BasicNameValuePair("sentenceId", dto.getSentenceId()));
		}
		if (dto.getSentenceType() != null) {
			params.add(new BasicNameValuePair("sentenceType", dto
					.getSentenceType()));
		}
		if (dto.getSentence() != null) {
			params.add(new BasicNameValuePair("sentence", dto.getSentence()));
		}
		
		if (dto.getFriendEmail() != null) {
			params.add(new BasicNameValuePair("friendEmail", dto
					.getFriendEmail()));
		}
		if (dto.getSeq() != null) {
			params.add(new BasicNameValuePair("seq", dto.getSeq()));
		}
		if (dto.getBlockYn() != null) {
			params.add(new BasicNameValuePair("blockYn", dto.getBlockYn()));
		}
		if (dto.getUserSex() != null) {
			params.add(new BasicNameValuePair("userSex", dto.getUserSex()));
		}
		if (dto.getUserAge() != null) {
			params.add(new BasicNameValuePair("userAge", dto.getUserAge()));
		}
		if (dto.getNewPassword() != null) {
			params.add(new BasicNameValuePair("newPassword", dto.getNewPassword()));
		}
		if (dto.getFriendName() != null) {
			params.add(new BasicNameValuePair("friendName", dto.getFriendName()));
		}
		
		params.add(new BasicNameValuePair("startIndex", ""+dto.getStartIndex()));
		return params;
	}

	public static void showNotify(String  msg,Context context){
    	Toast toast = Toast.makeText(context, msg ,
				Toast.LENGTH_SHORT);
//		toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
		toast.show();
    }
	
	private static boolean checkNetwokState(final Context mContext) {
		ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mobile = manager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		NetworkInfo wifi = manager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo lte_4g = manager
				.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);
		boolean blte_4g = false;
		if (lte_4g != null)
			blte_4g = lte_4g.isConnected();
		if (mobile.isConnected() || wifi.isConnected() || blte_4g)
			return true;
		else {

			// 여기는 걍 네트워크 상태 체크와 상관없는 연결이 잘 안될때 경고문 띄움 ㅋㅋ
			AlertDialog.Builder dlg = new AlertDialog.Builder(
					mContext);
			dlg.setTitle("네트워크 오류");
			dlg.setMessage("네트워크 상태를 확인해 주십시요.");
			//dlg.setIcon(R.drawable.icon36);
			dlg.setNegativeButton("종료", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					
					Activity activity = (Activity)mContext;
					activity.finish();
				}
			});
			dlg.setCancelable(false);
			dlg.show();
			return false;
		}
	}
	/**
	 * 2011-09-25 오진호
	 * 안드로이드의 버그로 인해 동일한 주소인데도 Marformed IPv6 관련 오류가 발생할 수 있다.
	 * 해당 부분을 해결하기 위해 아래와 같이 사용할수 있다.
	 * 참고 : http://stackoverflow.com/questions/6811482/use-url-on-android-throws-ioexception-malformed-ipv6-address
	 * 
	 * @param url
	 * @return
	 */
	public static URL getUrls(final String ourl) {
		KLog.d(ServerComunicationUtil.class,"getUrls", ourl);
		String[] vers = new String[4];
		String url = ourl.toString();
		URL rurl = null;
		try {
			if (url.toLowerCase().startsWith("http://")) vers[0]= "http";
			else if (url.toLowerCase().startsWith("https://")) vers[0] = "https";
			else vers[0]= "http"; 
			
			if (url.indexOf("://")>-1) {
				url = url.substring(url.indexOf("://")+3);
			}
			if (url.indexOf(":")>-1) {
				vers[1] = url.substring(0,url.indexOf(":"));
				vers[2] = url.substring(url.indexOf(":")+1, url.indexOf("/"));
			} else {
				vers[1] = url.substring(0,url.indexOf("/"));
				vers[2] = "80";
			}
			vers[3] = url.substring(url.indexOf("/"));
		}catch (Exception e) {
			KLog.e(ServerComunicationUtil.class, e);
			try {
				rurl = new URL(ourl);
			}catch (Exception e1){
				KLog.e(ServerComunicationUtil.class, e1);
			}
			return rurl;
		}
		
		try {
			rurl = new URL(vers[0], vers[1], Integer.parseInt(vers[2]), vers[3]);
		}	catch (Exception e) {
			KLog.e(ServerComunicationUtil.class, e);
		}
		return rurl;
	}
}
